<?php

namespace App\Services\Order;

use App\Models\CommodityActivity;
use App\Models\Order;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\Types\Integer;

abstract class OperationBase implements OrderOperation
{
    /**
     * 创建订单编号
     * @param string $type
     * @return string
     */
    protected function makeOrderNumbering(string $type = ''): string
    {
//        return strtoupper($type . Carbon::now()->format('YmdHis') . Str::random(6));
        // 老系统的订单生成方法: DateUtil.formatStringNow("yyMMddHHmmssSSS") + String.format("%04d", (int) (Math.random() * 10000)), PHP 毫秒 6位,所以在最后生成随机数字这里就剩一位即可
        return Carbon::now()->format('ymdHisu') . random_int(0, 9);
    }

    /**
     * 计算运费 免邮?
     * @param $activity
     * @param $number
     * @param $client
     * @return int
     */
    protected function calculationFreight($activity, $number, $client)
    {
        $freight = $activity['freight']; // 运费
        if ($freight > 0) {
            $minimal = $activity['free_shipping_minimal'];
            $maximum = $activity['free_shipping_maximum'];
            $satisfySingleMinimal = ($minimal > 0 && $maximum === 0) && $number >= $minimal; // eg: 满一件包邮
            $satisfySingleMaximum = ($minimal === 0 && $maximum > 0) && $number < $maximum; // eg: 小于五件包邮
            $satisfyMinimalAndMaximum = ($minimal > 0 && $maximum > 0) && ($number >= $minimal && $number < $maximum); // eg: 满一件 和 小于五件 包邮
            $noLimit = $minimal === 0 && $maximum === 0; // 没有限制
            if ($satisfySingleMinimal || $satisfySingleMaximum || $satisfyMinimalAndMaximum || $noLimit) {
                $freight = 0;
            }
        }

        // 计算偏远地区运费
        $remoteRegionsFreightSetting = arrayCombineByKey($activity['remote_regions_freight_setting'] ?? [], 'provinces');
        $clientProvince = (int) ($client['province']['code'] ?? 0);
        $remoteRegionsFreight = 0;
        // 偏远地区运费开启 && 在偏远地区范围内
        if ($activity['remote_regions_freight'] === CommodityActivity::REMOTE_REGIONS_FREIGHT_OPEN &&
            array_key_exists($clientProvince, $remoteRegionsFreightSetting)) {

            $setting = $remoteRegionsFreightSetting[$clientProvince];
            // 订单加价 和 sku 件数加价
            if ($setting['billing_method'] === CommodityActivity::BILLING_METHOD_BY_PIECE) { // 按照件数, sku * 每件加价
                $remoteRegionsFreight = $number * $setting['increase_amount'];
            } else if ($setting['billing_method'] === CommodityActivity::BILLING_METHOD_BY_ORDER) { // 按照订单
                $remoteRegionsFreight = $setting['increase_amount'];
            }
        }

        return $freight + $remoteRegionsFreight;
    }

    public function beforeHandle($order = null)
    {
    }

    public function afterHandle($order = null)
    {
    }
}
